package com.kaisu.blog.infrastructure.storage;

import cn.hutool.core.io.FileUtil;
import com.kaisu.blog.domain.file.File;
import com.kaisu.blog.domain.storage.Storage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;

/**
 * @author kaisu
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class LocalStorage implements Storage {

    @Value("${storage.local.directory}")
    private String localDirectory;
    @Value("${storage.local.preview.path}")
    private String serverPath;
    private final String separator = java.io.File.separator;

    @Override
    public void upload(InputStream fileStream, File file) {
        try {
            byte[] bytes = fileStream.readAllBytes();
            String path = generatePath(file.generateFileName());
            FileUtil.mkdir(FileUtil.getParent(path, 1));
            FileUtil.writeBytes(bytes, path);
            file.setMd5(DigestUtils.md5DigestAsHex(bytes));
            file.setStoragePath(getPath(file));
            file.setPreviewPath(getPreviewPath(file));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private String generatePath(String fileName) {
        return localDirectory.concat(separator).concat(LocalDate.now().toString()).concat(separator).concat(fileName);
    }

    @Override
    public String getPath(File file) {
        return generatePath(file.generateFileName());
    }

    @Override
    public String getPreviewPath(File file) {
        return serverPath.concat(file.getId());
    }
}
